package com.mce.nebula.controller;

import com.mce.nebula.dto.*;
import com.mce.nebula.service.AuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 认证控制器，对应Python的JWT Token View
 * @author 高露
 * @date 2025-09-20
 */
@Slf4j
@RestController
@RequestMapping("/users")
@Tag(name = "认证管理", description = "用户登录认证相关接口")
@RequiredArgsConstructor
public class AuthController {
    
    private final AuthService authService;
    
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录接口")
    public ResponseEntity<ApiResponse<LoginResponse>> login(LoginRequest loginRequest) {
        try {
            LoginResponse response = authService.login(loginRequest);
            return ResponseEntity.ok(ApiResponse.success(response, "登录成功"));
        } catch (BadCredentialsException e) {
            log.warn("Login failed for user: {}, reason: {}", loginRequest.getNickName(), e.getMessage());
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, "login_failed", e.getMessage()));
        } catch (Exception e) {
            log.error("Login error for user: {}", loginRequest.getNickName(), e);
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error(500, "internal_error", "系统内部错误"));
        }
    }
    
    @PostMapping("/logout")
    @Operation(summary = "用户登出", description = "用户登出接口")
    public ResponseEntity<ApiResponse<Void>> logout() {
        // JWT是无状态的，客户端删除token即可
        return ResponseEntity.ok(ApiResponse.success(null, "登出成功"));
    }
    
    @GetMapping("/check-user/{username}")
    @Operation(summary = "检查用户是否存在", description = "检查用户名是否已注册")
    public ResponseEntity<ApiResponse<Boolean>> checkUser(@PathVariable String username) {
        boolean exists = authService.userExists(username);
        return ResponseEntity.ok(ApiResponse.success(exists));
    }

    /**
     * 用户注册
     * @param request
     * @return
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "用户注册接口")
    public ResponseEntity<ApiResponse<LoginResponse>> register(UserRegisterRequest request) {
        try {
            LoginResponse response = authService.register(request);
            return ResponseEntity.ok(ApiResponse.success(response, "注册成功"));
        } catch (Exception e) {
            log.error("Registration error for user: {}", request.getUserName(), e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, "registration_failed", e.getMessage()));
        }
    }
    
    @PostMapping("/send-reset-email")
    @Operation(summary = "发送密码重置邮件", description = "发送忘记密码邮件")
    public ResponseEntity<ApiResponse<Void>> sendResetEmail(@RequestParam String email) {
        try {
            authService.sendResetEmail(email);
            return ResponseEntity.ok(ApiResponse.success(null, "邮件发送成功"));
        } catch (Exception e) {
            log.error("Send reset email error for: {}", email, e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, "send_email_failed", e.getMessage()));
        }
    }
    
    @PostMapping("/reset-password")
    @Operation(summary = "重置密码", description = "通过邮件链接重置密码")
    public ResponseEntity<ApiResponse<Void>> resetPassword(
            @RequestParam String tag,
            @Valid @RequestBody PasswordResetRequest request) {
        try {
            authService.resetPassword(tag, request);
            return ResponseEntity.ok(ApiResponse.success(null, "密码重置成功"));
        } catch (Exception e) {
            log.error("Reset password error", e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, "reset_password_failed", e.getMessage()));
        }
    }
    
    @PostMapping("/change-password")
    @Operation(summary = "修改密码", description = "修改用户密码")
    public ResponseEntity<ApiResponse<Void>> changePassword(@Valid @RequestBody ChangePasswordRequest request) {
        try {
            authService.changePassword(request);
            return ResponseEntity.ok(ApiResponse.success(null, "密码修改成功"));
        } catch (Exception e) {
            log.error("Change password error", e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, "change_password_failed", e.getMessage()));
        }
    }
    
    @GetMapping("/user-details")
    @Operation(summary = "获取用户详情", description = "获取当前用户的详细信息")
    public ResponseEntity<ApiResponse<UserDetailsResponse>> getUserDetails(@RequestParam(required = false) String teamName) {
        try {
            UserDetailsResponse response = authService.getUserDetails(teamName);
            return ResponseEntity.ok(ApiResponse.success(response));
        } catch (Exception e) {
            log.error("Get user details error", e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, "get_user_details_failed", e.getMessage()));
        }
    }
    
    @PutMapping("/user-details")
    @Operation(summary = "更新用户信息", description = "更新用户基本信息")
    public ResponseEntity<ApiResponse<Void>> updateUserDetails(@RequestBody UserDetailsResponse request) {
        try {
            authService.updateUserDetails(request);
            return ResponseEntity.ok(ApiResponse.success(null, "用户信息更新成功"));
        } catch (Exception e) {
            log.error("Update user details error", e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, "update_user_details_failed", e.getMessage()));
        }
    }
    
    @GetMapping("/favorites")
    @Operation(summary = "获取用户收藏", description = "获取用户收藏列表")
    public ResponseEntity<ApiResponse<List<UserFavoriteResponse>>> getUserFavorites() {
        try {
            List<UserFavoriteResponse> favorites = authService.getUserFavorites();
            return ResponseEntity.ok(ApiResponse.success(favorites));
        } catch (Exception e) {
            log.error("Get user favorites error", e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, "get_favorites_failed", e.getMessage()));
        }
    }
    
    @PostMapping("/favorites")
    @Operation(summary = "添加用户收藏", description = "添加新的用户收藏")
    public ResponseEntity<ApiResponse<Void>> addUserFavorite(@Valid @RequestBody UserFavoriteRequest request) {
        try {
            authService.addUserFavorite(request);
            return ResponseEntity.ok(ApiResponse.success(null, "收藏添加成功"));
        } catch (Exception e) {
            log.error("Add user favorite error", e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, "add_favorite_failed", e.getMessage()));
        }
    }
    
    @PutMapping("/favorites/{favoriteId}")
    @Operation(summary = "更新用户收藏", description = "更新用户收藏信息")
    public ResponseEntity<ApiResponse<Void>> updateUserFavorite(
            @PathVariable Integer favoriteId,
            @Valid @RequestBody UserFavoriteRequest request) {
        try {
            authService.updateUserFavorite(favoriteId, request);
            return ResponseEntity.ok(ApiResponse.success(null, "收藏更新成功"));
        } catch (Exception e) {
            log.error("Update user favorite error", e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, "update_favorite_failed", e.getMessage()));
        }
    }
    
    @DeleteMapping("/favorites/{favoriteId}")
    @Operation(summary = "删除用户收藏", description = "删除用户收藏")
    public ResponseEntity<ApiResponse<Void>> deleteUserFavorite(@PathVariable Integer favoriteId) {
        try {
            authService.deleteUserFavorite(favoriteId);
            return ResponseEntity.ok(ApiResponse.success(null, "收藏删除成功"));
        } catch (Exception e) {
            log.error("Delete user favorite error", e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(400, "delete_favorite_failed", e.getMessage()));
        }
    }
}


